GLOBAL.setmetatable(env, { __index = function(t, k) return GLOBAL.rawget(GLOBAL, k) end })

-- 可调参数
local PICKUP_RADIUS = 20
local TICK          = 6   -- 每 6 帧扫描一次
local FLY_SPEED     = 12  -- 飞行速度（单位/秒）
local SNAP_DIST     = 1.5 -- 直接进包的距离

------------------------------------------------------------------
-- 把单个余烬吸向指定玩家
local function LaunchToPlayer(inst, player)
    if not inst:IsValid() or not player:IsValid() then return end
    if inst._flytask then return end -- 已经在飞

    inst._flytask = inst:DoPeriodicTask(FRAMES, function()
        if not player:IsValid() or not inst:IsValid() then
            if inst._flytask then
                inst._flytask:Cancel()
                inst._flytask = nil
            end
            return
        end

        local px, py, pz = player.Transform:GetWorldPosition()
        local ix, iy, iz = inst.Transform:GetWorldPosition()
        local dx, dz = px - ix, pz - iz
        local dist = math.sqrt(dx * dx + dz * dz)

        if dist <= SNAP_DIST then
            -- 进背包
            if player.components.inventory  then
                player.components.inventory:GiveItem(inst)
            end
            if inst._flytask then
                inst._flytask:Cancel()
                inst._flytask = nil
            end
            return
        end

        -- 平滑移动
        local step = FLY_SPEED * FRAMES
        local nx, nz = ix + dx / dist * step, iz + dz / dist * step
        inst.Transform:SetPosition(nx, 0, nz)
    end)
end

------------------------------------------------------------------
-- 全局扫描器
local function kaiguan()
    local willows = {}
    for _, v in ipairs(AllPlayers) do
        if v:HasTag("ember_master") and v:IsValid() then
            table.insert(willows, v)
        end
    end
    if #willows == 0 then return end

    for _, w in ipairs(willows) do
        local x, y, z = w.Transform:GetWorldPosition()
        local embers = TheSim:FindEntities(x, y, z, PICKUP_RADIUS, { "willow_ember" })
        for _, em in ipairs(embers) do
            if em:IsValid() and
                em.entity:IsVisible() and
                not (em.components.inventoryitem and em.components.inventoryitem:IsHeld()) then
                LaunchToPlayer(em, w)
            end
        end
    end
end

------------------------------------------------------------------
AddModRPCHandler('mymod', "pickitems", function(inst)
    if not inst or not inst:IsValid() or inst:HasTag("playerghost") then return end
    if inst.kaiguan == nil then
        inst.kaiguan = inst:DoPeriodicTask(3, kaiguan, 0)
        if inst.components.talker then
            inst.components.talker:Say("自动拾取以太余烬功能已开启")
        end
    elseif inst.kaiguan ~= nil then
        inst.kaiguan:Cancel()
        inst.kaiguan = nil
        if inst.components.talker then
            inst.components.talker:Say("自动拾取以太余烬功能已关闭")
        end
    end
end)
AddPlayerPostInit(function(inst)
    inst:DoTaskInTime(0, function()
        if inst == ThePlayer and inst.prefab == "willow" then
            -- 手杖快速拾取键
            TheInput:AddKeyDownHandler(KEY_R, function()
                local screen = TheFrontEnd:GetActiveScreen()
                local IsHUDActive = screen and screen.name == "HUD"
                if inst:IsValid() and IsHUDActive and ThePlayer.HUD and not ThePlayer.HUD:HasInputFocus() then
                    SendModRPCToServer(GetModRPC('mymod', "pickitems"))
                end
            end)
        end
    end)
end)
